package com.sap.sap_mangers.controller;

import com.sap.sap_mangers.Vo.UserVo.UserMessage;
import com.sap.sap_mangers.service.BillService;
import com.sap.sap_mangers.service.CacheService;
import com.sap.sap_mangers.service.DynamicService;
import com.sap.sap_mangers.service.UserService;
import com.sap.sap_mangers.until.ConstantUntil;
import com.sap.sap_mangers.until.JwtUtil;
import com.sap.sap_mangers.until.SimpleJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author 阿东
 * @date 2022/8/29 [14:59]
 */
@RestController
@RequestMapping("/Bill")
public class BillController {
    @Autowired
    private UserService userService;
    @Autowired
    private BillService billService;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private DynamicService dynamicService;

    /**
     * 添加支出账单
     *
     * @param request http请求
     * @return 视图
     */
    @PreAuthorize("hasAuthority('会长')")
    @PostMapping("/addBill")
    public SimpleJson addBill(HttpServletRequest request) {
        String userForToken = JwtUtil.getUserForToken();
        UserMessage userMessage = userService.getUserMessage(userForToken);
        if (userMessage.getRole() > ConstantUntil.ROLE_SECRETARY_OF_THE_LEAGUE) {
            return new SimpleJson(1, "权限不足，无法操作!只允许会长或者团支书操作该接口");
        }
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
        String money = params.getParameter("money");
        BigDecimal price;
        try {
            price = BigDecimal.valueOf(Double.parseDouble(money));
        } catch (Exception e) {
            e.printStackTrace();
            return new SimpleJson(1, "消费金额格式错误!");
        }
        String context = params.getParameter("context");
        if (context.length() > 32) {
            return new SimpleJson(1, "标题过长!");
        }
        String time = params.getParameter("time");
        Timestamp timestamp;
        try {
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(time);
            timestamp = new Timestamp(date.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
            return new SimpleJson(1, "日期格式错误");
        }
        String note = params.getParameter("note");
        if (note.length() > 255) {
            return new SimpleJson(1, "备注过长!");
        }
        List<MultipartFile> images = ((MultipartHttpServletRequest) request).getFiles("images");

        //事务处理
        try {
            return billService.addBill(0, context, price, timestamp, note, images, userForToken, cacheService.getRealNameCache(cacheService.getRealNameCacheMap(), userForToken));
        } catch (SQLException sqlException) {
            //当对数据库操作发生异常时，返回失败 (先捕获SQLException,因为Exception是其父类)
            return SimpleJson.FAILURE;
        } catch (IOException e) {
            //当图片格式不正确时主动抛出Exception，返回提示信息
            return new SimpleJson(1, "图片格式不正确");
        } catch (Exception exception) {
            exception.printStackTrace();
            return SimpleJson.FAILURE;
        }
    }

    @PreAuthorize("hasAuthority('旧管理员')")
    @GetMapping("/getSumRevenue")
    public SimpleJson getSumRevenue() {
        return new SimpleJson(billService.getSumBill(1, Integer.valueOf(dynamicService.getYear())));
    }

    @PreAuthorize("hasAuthority('旧管理员')")
    @GetMapping("/getSumRevenueByYear")
    public SimpleJson getSumRevenueByYear(@RequestParam("year") Integer year) {
        return new SimpleJson(billService.getSumBill(1, year));
    }

    @PreAuthorize("hasAuthority('旧管理员')")
    @GetMapping("/getSumSpending")
    public SimpleJson getSumSpending() {
        return new SimpleJson(billService.getSumBill(0, Integer.valueOf(dynamicService.getYear())));
    }

    @PreAuthorize("hasAuthority('旧管理员')")
    @GetMapping("/getSumSpendingByYear")
    public SimpleJson getSumSpendingByYear(@RequestParam("year") Integer year) {
        return new SimpleJson(billService.getSumBill(0, year));
    }

    @PreAuthorize("hasAuthority('旧管理员')")
    @GetMapping("/getBillSpending")
    public SimpleJson getBillSpending() {
        return new SimpleJson(billService.getBill(0, Integer.valueOf(dynamicService.getYear())));
    }

    @PreAuthorize("hasAuthority('旧管理员')")
    @GetMapping("/getBillSpendingByYear")
    public SimpleJson getBillSpendingByYear(@RequestParam("year") Integer year) {
        return new SimpleJson(billService.getBill(0, year));
    }

    @PreAuthorize("hasAuthority('旧管理员')")
    @GetMapping("/getBillRevenue")
    public SimpleJson getBillRevenue() {
        return new SimpleJson(billService.getBill(1, Integer.valueOf(dynamicService.getYear())));
    }

    @PreAuthorize("hasAuthority('旧管理员')")
    @GetMapping("/getBillRevenueByYear")
    public SimpleJson getBillRevenueByYear(@RequestParam("year") Integer year) {
        return new SimpleJson(billService.getBill(1, year));
    }

}
